const express = require('express');
const router = express.Router();
const { query } = require('../db/index')
const jsonWebToken = require('jsonwebtoken')
const menuList=require('../db/menu')

const code = {
    0: '请求失败',
    200: '请求成功',
    403: 'token未携带',
    404: 'token已失效'
}

//路由全局拦截器
router.requestLJQ = ((request, response, next) => {
    console.log('route路径:', request.url)
    const noPermissionRoutes = ['/api/login']
    if (noPermissionRoutes.includes(request.url)) return next()
    const token = request.headers.authorization
    if (!token) return response.send({ code: 403, message: code[403] })
    jsonWebToken.verify(token, "fubing", (err, res) => {
        if (err)  return response.send({ code: 404, message: code[404] })
        // console.log('authorization', res, err)
        request.tokenData = res
        next()
    })

})


router.get('/index.html', (request, response) => {
    response.sendFile('/index.html')
})


//登录
router.post('/login', async (request, response) => {
    const params = request.body
    const data = await query("select * from user where userName=? and password=?", [params.userName, params.password])
    if (data.length === 0) return response.json({ code: 0, message: '用户名或密码错误' })
    jsonWebToken.sign({ id: data[0].id }, 'fubing', { expiresIn: 60 * 60 * 24 }, async (err, token) => {
        if (err) {
            console.log('token生成失败', err)
        }
        data[0].token = token
        await query('update user set token=? where userName=?', [token, params.userName])
        response.json({ code: 200, data: data[0], message: '登录成功' })
    })

})

//登出
router.get('/logout', async (request, response) => {
    await query("update user set token=''")
    response.json({ code: 200, data:null, message: '登出成功' })

})

router.get('/getUserList', async (request, response) => {
    const data = await query("select id,userName,roleId,createTime,updateTime from user")
    response.json({ code: 200, data})
})

router.get('/getMenuList', async (request, response) => {
    response.json({ code: 200, data:menuList })
})

router.get('/request', async (request, response) => {
    response.send({ code: 200, request: request.url })
})


module.exports = router



